//
//  MainViewController.swift
//  RoundCatPlay2
//
//  Created by 姜澎 on 2019/10/18.
//  Copyright © 2019 jiangpeng. All rights reserved.
//

import UIKit
import SnapKit
import SwiftTTPageController
class MainViewController: UITableViewController {
    
    
    //    轮播图
    private lazy var cycleView :CycleView = {
        
        //        状态栏 + 导航条
        //        let pointY = 44 + UIApplication.shared.statusBarFrame.size.height
        let y = 0
        let x = 0
        let width = Int(UIScreen.main.bounds.size.width)
        let height = 180
        
        let cycleView : CycleView = CycleView(frame: CGRect(x: x, y: y, width: width, height: height))
        //本地图片测试--加载网络图片,请用第三方库如SDWebImage等
        cycleView.imageURLStringArr = ["组37.jpg", "组37.jpg", "组37.jpg"]
        cycleView.delegate = self
        return cycleView
    }()
    
    //    search
    private var searchBar: UISearchBar = {
        var search = UISearchBar(frame: CGRect(x: 0, y: 0, width:Int(UIScreen.main.bounds.size.width), height: 100))
        search.barStyle = .blackOpaque // 背景颜色
        search.tintColor = UIColor.gray
        search.placeholder = "请输入陪玩师名称"
        return search
    }()
    
    // MARK: 顶部 集合视图
    private lazy var topCollectionView: UIView = {
        let view = UIView()
        view.layer.cornerRadius = 10
        view.backgroundColor = .white
        view.addSubview(self.topCollection)
        view.addSubview(self.topBtu)
        return view
    }()
    
    private lazy var topCollection : UICollectionView = {
        
        let oneLineSource: Int = 4
        let spacingWidth: Int = 20
        let spacingCount: Int = oneLineSource + 1
        let iphoneWith: Int = Int(UIScreen.main.bounds.width)
        let countSource: Int = 8
        
        let flow = UICollectionViewFlowLayout()
        //        算法 一行必须是几个
        let flowW = (iphoneWith - spacingWidth * spacingCount) / oneLineSource
        let flowH = 80
        flow.itemSize = CGSize(width: flowW, height: flowH)
        flow.minimumLineSpacing = 10
        flow.minimumInteritemSpacing = 10
        flow.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        
        let topColllection = UICollectionView(frame: .zero, collectionViewLayout: flow)
        topColllection.register(TopCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        topColllection.dataSource = self
        topColllection.delegate = self
        topColllection.backgroundColor = .white
        return topColllection
    }()
    
    private lazy var topCollectionDataSourceArr:[TopCellModel] = {
        var nameArr:[String] = ["和平精英","王者荣耀","绝地求生","英雄联盟","Dota2","声优聊天","唱歌","叫醒管家"]
        var arr = [TopCellModel]()
        
        for i in 0..<nameArr.count {
            let m = TopCellModel(imagView: "\(i)", imageNma: nameArr[i])
            arr.append(m)
        }
        
        return arr
    }()
    
    
    private lazy var topBtu:UIButton = {
        let btu = UIButton(type: .custom)
        btu.setImage(UIImage(named: "广告"), for: .normal)
        btu.setImage(UIImage(named: "广告"), for: .highlighted)
        return btu
    }()
    
    
    
    // MARK 底部集合视图   test star
    private lazy var bottomCollection: UICollectionView = {
        let flow = UICollectionViewFlowLayout()
        let iphoneWihtd = UIScreen.main.bounds.width - 40
        let spacingWith = 6
        let sourcesNumLine = 2
        let flowWidth = (Int(iphoneWihtd) - spacingWith * (sourcesNumLine + 1)) / sourcesNumLine
        flow.itemSize = CGSize(width:  flowWidth , height: 240)
        flow.minimumInteritemSpacing = 5
        flow.minimumLineSpacing = 20
        flow.sectionInset = UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 20)
        
        let bc = UICollectionView(frame: .zero, collectionViewLayout: flow)
        bc.dataSource = self
        bc.delegate = self
        bc.register(BottomCollectionViewCell.self, forCellWithReuseIdentifier: "cell2")
        bc.backgroundColor = UIColor.white
        // 取竖着cell的个数  总数 除以 每行两个 等于 能放几行
        let num2 = Int(round(7 / 2)) //向上取整   collection源数据个数...........................
        bc.frame = CGRect(x: 0, y: 0, width: Int(UIScreen.main.bounds.width), height: num2 * 240 + (20 * (num2+1)))  // 高度的总数 加上 边距的总数
        bc.backgroundColor = UIColor(red: 247/255, green: 247/255, blue: 247/255, alpha: 1)
        return bc
    }()
    
    let titless = ["和平精英","王者荣耀","绝地求生","英雄联盟","Dota2","声优聊天","唱歌","叫醒管家"]
    
    private lazy var headView: TTHeadView = {
        let headView = TTHeadView (frame: CGRect (x: 15 , y: 0, width: UIScreen.main.bounds.width - 35, height: 40), titles: titless, delegate: self)
        
        return headView
    }()
    
    private lazy var tableViewHeadView :UIView = {
        let v = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 40))
        v.addSubview(self.headView)
        v.backgroundColor = UIColor(red: 247/255, green: 247/255, blue: 247/255, alpha: 1)
        return v
    }()
    
    fileprivate lazy var pageContentView : TTPageViewController = {
        var childVCArr = [UIViewController]()
        for i in 0...8{
            //
            let v = UIViewController() // 添加五个cllection *********************
            
            
//            let red = CGFloat(arc4random()%256)/255.0
//            let green = CGFloat(arc4random()%256)/255.0
//            let blue = CGFloat(arc4random()%256)/255.0
//            v.view.backgroundColor =  UIColor(red: red, green: green, blue: blue, alpha: 1)
            if i == 0 {
                v.view.addSubview(self.bottomCollection)
            }
            childVCArr.append(v)
        }
        
        let frame = CGRect (x: 0, y: 0,width: UIScreen.main.bounds.width, height: self.bottomCollection.frame.height)
        
        let pagevc = TTPageViewController.init(controllers: childVCArr, frame: frame, delegate: self)
        return pagevc
    }()
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        setTopCollectionFream()
        setTopButtonFream()
        
//        导航栏底线设置透明
        self.navigationController?.navigationBar.shadowImage = UIImage()
    
        // 导航栏的背景颜色
        self.navigationController?.navigationBar.barTintColor = UIColor(red: 70/255, green: 47/255, blue: 229/255, alpha: 1)
        //        导航栏上的搜索框
        let leftNavBarButton = UIBarButtonItem(customView:searchBar)
        self.navigationItem.leftBarButtonItem = leftNavBarButton
        
        
        //        取消表格的下划线
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "topcell")
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "bottomcell")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
//        self.backImage = self.navigationController?.navigationBar.backIndicatorImage
//        self.shadowImage = self.navigationController?.navigationBar.shadowImage
        self.navigationController?.navigationBar.isTranslucent = true  // 取消将要显示的时候 导航栏半透明效果
    }
    

    
//    override func viewWillDisappear(_ animated: Bool) {
//        super.viewWillDisappear(animated)
//        self.navigationController?.navigationBar.shadowImage = shadowImage
//        self.navigationController?.navigationBar.setBackgroundImage(backImage, for: .default)
//
//    }

    
}

//首页的数据源方法
extension MainViewController{
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        
        return 2
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
        
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "topcell")
            cell!.contentView.addSubview(cycleView)
            cell!.contentView.addSubview(topCollectionView)
            cell!.selectionStyle = .none
            cell!.backgroundColor = UIColor(red: 249/255.0, green: 249/255.0, blue: 249/255.0, alpha: 1)
            setTopViewUIFream()
            return cell!
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "bottomcell")
                        cell!.contentView.addSubview(self.pageContentView.view)
            return cell!
        }
        
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 490
        }else {
            return self.bottomCollection.frame.size.height
        }
        
    }
    
    func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if section == 1 {
            return self.tableViewHeadView
        }else {
            return UIView()
        }
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 {
            return 40
        }else{
            return 0
        }
    }
    
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let offset = scrollView.contentOffset.y
        
        //第一种：系统导航栏，利用push跳转，但是有个问题是状态栏的颜色未渐变
        if offset<50 {
            //滑倒底部之前

            self.navigationController?.navigationBar.barTintColor = UIColor(red: 70/255, green: 47/255, blue: 229/255, alpha: 1)
            self.searchBar.barStyle = .blackOpaque

        }else{
            //滑动超过导航栏底部
            let coloralph = offset / 100
            self.navigationController?.navigationBar.barTintColor = UIColor.white.withAlphaComponent(coloralph)
            self.searchBar.barStyle = .default
        }
        
    }
}

//Top 集合视图的数据源 代理方法
extension MainViewController: UICollectionViewDataSource,UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if collectionView.isEqual(self.topCollection) {
            return self.topCollectionDataSourceArr.count
        }else if collectionView.isEqual(self.bottomCollection){
            return 7
        }else {
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionView.isEqual(self.topCollection) {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)  as! TopCollectionViewCell
            cell.cellModel = self.topCollectionDataSourceArr[indexPath.row]
            return cell
        }else if collectionView.isEqual(self.bottomCollection){
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell2", for: indexPath) as! BottomCollectionViewCell
//            cell.DwLable.text = "adfasdf"
            return cell
        }else {
            return UICollectionViewCell()
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if collectionView.isEqual(self.topCollection){
            
            
        }else if collectionView.isEqual(self.bottomCollection){
            self.navigationController?.pushViewController(ImmediatelyDDViewController(), animated: false)
        }else {
            
            
        }
       
    }
    
    
}

extension MainViewController: TTHeadViewDelegate,TTPageViewControllerDelegate {
    func tt_headViewSelectedAt(_ index: Int) {
         pageContentView.scrollToPageAtIndex(index)
    }
    
    func tt_pageControllerSelectedAt(_ index: Int) {
        headView.scrollToItemAtIndex(index)
    }
    
    
}


//子控件的布局
extension MainViewController {
    func setTopViewUIFream(){
        self.topCollectionView.snp.makeConstraints { (make) in
            make.top.equalTo(self.cycleView.snp_bottom).offset(-15)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(315)
        }
    }
    func setTopCollectionFream(){
        self.topCollection.snp.makeConstraints { (make) in
            make.top.equalTo(self.topCollectionView.snp_top).offset(20)
            make.left.equalTo(self.topCollectionView.snp_left)
            make.right.equalTo(self.topCollectionView.snp_right)
            make.height.equalTo(190)
        }
    }
    func setTopButtonFream(){
        self.topBtu.snp.makeConstraints { (make) in
            make.top.equalTo(self.topCollection.snp_bottom).offset(0)
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.height.equalTo(90)
        }
    }
    
    func setScrollerViewFrame(){
        self.headView.snp.makeConstraints { (make) in
            make.right.equalTo(-20)
            make.left.equalTo(20)
            make.top.equalTo(0)
            make.bottom.equalTo(0)
        }
    }
    
}

//轮播图的代理方法
extension MainViewController : CycleViewDelegate{
    func cycleViewDidSelectedItemAtIndex(_ index: NSInteger) {
        print("我选中了第\(index)张图片")
    }
    
    
}


